#include "tcp_client.h"

tcp_client::tcp_client(uint32 ip,uint16 port)
{
	func_lock s_lock;
   m_log = new logfile("tcp_client");
   my_sock=socket(AF_INET,SOCK_STREAM,0);
   
   setnonblocking(my_sock);
   m_ip = ip;
   m_port = port;
   
   if(my_sock == -1)
	   m_log->WriteTrace(" create socket error");
}

tcp_client::~tcp_client()
{
	func_lock s_lock;
	delete m_log;

   char ll[1024] = {0};
   sprintf(ll,"close socket=%d",my_sock);
   m_log->WriteTrace(ll);

	if(my_sock != -1 )
	   close(my_sock);
}

void tcp_client::setnonblocking(uint32 socket)
{
	int opts;
	opts=fcntl(socket,F_GETFL);
	if(opts<0)
	{
		return;
	}

	opts = opts|O_NONBLOCK;
	if(fcntl(socket,F_SETFL,opts)<0)
	{
		return;
	}
}

bool tcp_client::con()
{
   m_sock_addr.sin_family=AF_INET;
   m_sock_addr.sin_port= htons(m_port);
   memcpy(&m_sock_addr.sin_addr,&m_ip,sizeof(uint32));
   sockaddr in_addr;
   
   memcpy(&in_addr,&m_sock_addr,sizeof(sockaddr));

   int n = connect(my_sock,&in_addr,sizeof(sockaddr));
  
   /*char ll[1024] = {0};
   sprintf(ll,"socket client con,socket=%d,n=%d,errno=%d",
	   my_sock,n,errno);
   m_log->WriteTrace(ll);*/

   if(n !=0)
       m_con = false;

   m_con =  true;
   return m_con;
}

int tcp_client::sendbuf(char* buf, uint32 buf_size)
{
	func_lock s_lock;
	if(my_sock == -1)
	{
		m_log->WriteTrace("send buf error");
	    return false;
	}

	if(m_con == false)
	{
		if( con() == false)
			return 0;
	}

     int n = send(my_sock,buf,buf_size,0);

	 if(n ==-1 && errno != EAGAIN)
	 {
		 return 0;
		 m_log->WriteTrace("send error");
	 };

	 if(n == -1)
	    n=0;

	 return n;
}

uint32 tcp_client::get_socket()
{
	return my_sock;
}